;(function($) {
	$.fn.extend({
		makeDraggable: function(o) {
			return this.each(function() { 
				if(!$.data(this, "ui-draggable")){
					 new $.ui.draggable(this,o);	
				}
			});
		},
		removeDraggable: function() {
			return this.each(function() { 
				if($.data(this, "ui-draggable")){
					 $.data(this, "ui-draggable").destroy();
				} 
			});
		}
	});
	
	//If the UI scope is not available, add it
	$.ui = $.ui || {};
	
	
	$.fn.extend({
		mouseInteraction: function(o) {
			return this.each(function() {
				new $.ui.mouseInteraction(this, o);
			});
		},
		removeMouseInteraction: function(o) {
			return this.each(function() {
				if($.data(this.element, "ui-mouse"))
				    //调用$.ui.mouseInteraction的destroy方法
					$.data(this.element, "ui-mouse").destroy();
			});
		}
	});
	
	//constructor
	$.ui.mouseInteraction = function(element, options) {
	
		var self = this;
		this.element = element;
		$.data(this.element, "ui-mouse", this);
		this.options = $.extend({}, options);
		
		//响应mousedown事件，传入参数e
		$(element).bind('mousedown.draggable', function() { 
			return self.click.apply(self, arguments); }
		);
		if($.browser.msie){
			 $(element).attr('unselectable', 'on'); //Prevent text selection in IE
		}

	};
	
	$.extend($.ui.mouseInteraction.prototype, {
		
		destroy: function() { 
			this.element.unbind('mousedown.draggable'); 
		},
		
		trigger: function() { 
			return this.click.apply(this, arguments); 
		},
		
		//mousedown，鼠标点击事件发生后，将mouseup和mousemove绑定到相应用处理方法上
		click: function(e) {
			
			if(
				   e.which != 1 //only left click starts dragging
				|| $.inArray(e.target.nodeName.toLowerCase(), this.options.dragPrevention) != -1 // Prevent execution on defined elements
				|| (this.options.condition && !this.options.condition.apply(this.options.executor || this, [e])) //Prevent execution on condition
			) return true;
			
			var self = this;
			
			var initialize = function() {
				window.focus();
				//_MP : mouse position
				self._MP = { left: e.pageX, top: e.pageY }; // Store the click mouse position
				$(document).bind('mouseup.draggable', function() { 
						return self.stop.apply(self, arguments); }
					);
				$(document).bind('mousemove.draggable', function() { 
						return self.drag.apply(self, arguments); }
					);
			};

			//初始化draggable
			if(this.options.delay) {
				if(this.timer){
					 clearInterval(this.timer);
				}
				this.timer = setTimeout(initialize, this.options.delay);
			} else {
				initialize();
			}
			
			return false;
		},
		
		//响应mouseup
		stop: function(e) {			
			
			var o = this.options;
			if(!this.initialized){
				 return $(document).unbind('mouseup.draggable').unbind('mousemove.draggable');
			}

			if(this.options.stop){
				 //调用executor的stop方法,这里是draggable
				 this.options.stop.call(this.options.executor || this, e);
			}
			
			//解除绑定
			$(document).unbind('mouseup.draggable').unbind('mousemove.draggable');
			this.initialized = false;
			return false;
			
		},
		//响应mousemove
		drag: function(e) {

			var o = this.options;
			if ($.browser.msie && !e.button){
				 return this.stop.apply(this, [e]); // IE mouseup check
			}
			
			//如果还没有初始化，当helper和原DOM元素的距离大于o.distance时，认为开始拽
			if(!this.initialized && (Math.abs(this._MP.left-e.pageX) >= o.distance || Math.abs(this._MP.top-e.pageY) >= o.distance)) {
				if(this.options.start){
					 //调用draggable的start方法
					 this.options.start.call(this.options.executor || this, e);
				}
				this.initialized = true;
			} else {  //已经初始化过，不必再次初始化
				if(!this.initialized){
					 return false;
				}
			}

			if(o.drag){
				 o.drag.call(this.options.executor || this, e);
			}
			
			return false;
		}
	});
	
	/************************************ draggable ********************************************/
	$.ui.draggable = function(element, options) {
		//Initialize needed constants
		var self = this;
		this.element = $(element);
		$.data(element, "ui-draggable", this);
		this.element.addClass("ui-draggable");
		
		//Prepare the passed options
		this.options = $.extend({}, options);
		var o = this.options;
		$.extend(o, {
			helper: o.ghosting == true ? 'clone' : (o.helper || 'original'),
			handle : o.handle ? ($(o.handle, element)[0] ? $(o.handle, element) : this.element) : this.element,
			appendTo: o.appendTo || 'parent'		
		});
		
		//Initialize mouse events for interaction
		//初始化options
		//这里将拖拽事件和具体的处理函数绑定到了一起
		$(o.handle).mouseInteraction({
			executor: this,      //当前对象为executor
			delay: o.delay,
			distance: o.distance || 0,
			dragPrevention: o.prevention ? o.prevention.toLowerCase().split(',') : ['input','textarea','button','select','option'],
			start: this.start,  //刚开始拖拽时调用
			stop: this.stop,	//响应mouseup事件
			drag: this.drag,    //响应mousemove
			condition: function(e) { 
				return !(e.target.className.indexOf("ui-resizable-handle") != -1 || this.disabled); 
			}
		});
		
		//Position the node
		if(o.helper == 'original' && (this.element.css('position') == 'static' || this.element.css('position') == ''))
			this.element.css('position', 'relative');
		
	};
	
	$.extend($.ui.draggable.prototype, {
		ui: function(e) {
			return {
				helper: this.helper,
				position: this.position,
				absolutePosition: this.positionAbs,
				instance: this,
				options: this.options					
			};
		},
		propagate: function(n,e) {
			this.element.triggerHandler(n == "drag" ? n : "drag"+n, [e, this.ui()], this.options[n]);
		},
		destroy: function() {
			this.element.removeClass("ui-draggable ui-draggable-disabled");
			this.handle.removeMouseInteraction();
		},
		enable: function() {
			this.element.removeClass("ui-draggable-disabled");
			this.disabled = false;
		},
		disable: function() {
			this.element.addClass("ui-draggable-disabled");
			this.disabled = true;
		},
		start: function(e) {
			
			var o = this.options;
			
			//Create and append the visible helper
			//拖拽时显示的辅助元素
			this.helper = typeof o.helper == 'function' ? $(o.helper.apply(this.element[0], [e])) : (o.helper == 'clone' ? this.element.clone().appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo)) : this.element);
			if(this.helper[0] != this.element[0]){
				 this.helper.css('position', 'absolute');
			}

			//Find out the next positioned parent
			//offsetparent: Retrieves a reference to the container object that defines the offsetTop and offsetLeft properties of the object
			//元素的offsetParent是元素的第一个绝对定位或者相对定位的parent? 大多数情况下是body?
			this.offsetParent = (function(cp) {
				while(cp) {
					if(cp.style && (/(absolute|relative|fixed)/).test($.css(cp,'position'))){
						 return $(cp);
					}
					cp = cp.parentNode ? cp.parentNode : null;
				}; 
				return $("body");		
			})(this.helper[0].parentNode);
			
			//Prepare variables for position generation
			this.elementOffset = this.element.offset();
			this.offsetParentOffset = this.offsetParent.offset();
			//elementPosition: 定位helper的位置
			var elementPosition = { left: this.elementOffset.left - this.offsetParentOffset.left, top: this.elementOffset.top - this.offsetParentOffset.top };
			
			this._pageX = e.pageX; 
			this._pageY = e.pageY;
			
			//clickOffset:鼠标相对于element的位置差
			this.clickOffset = { left: e.pageX - this.elementOffset.left, top: e.pageY - this.elementOffset.top };
			var r = this.helper.css('position') == 'relative';

			//Generate the original position
			//helper最初的位置
			this.originalPosition = {
				left: (r ? parseInt(this.helper.css('left')) || 0 : elementPosition.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft)),
				top: (r ? parseInt(this.helper.css('top')) || 0 : elementPosition.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop))
			};
			
			//Generate a flexible offset that will later be subtracted from e.pageX/Y
			this.offset = {left: e.pageX - this.originalPosition.left, top: e.pageY - this.originalPosition.top };
			
			
			//Call plugins and callbacks
			//修改过，只调用callbacks
			this.propagate("start", e);

			this.helperProportions = { width: this.helper.outerWidth(), 
									   height: this.helper.outerHeight()};
									   

			return false;

		},
		clear: function() {
			this.helper = null;
		},
		
		//mouse up时调用
		stop: function(e) {
			//Call plugins and trigger callbacks
			this.propagate("stop", e);
			
			if(this.cancelHelperRemoval) return false;			
			if(this.options.helper != 'original') {
				this.helper.remove();
			}
			this.clear();
			return false;
		},
		drag: function(e) {
			//Compute the helpers position
			this.position = { top: e.pageY - this.offset.top, left: e.pageX - this.offset.left };
			this.positionAbs = { left: e.pageX - this.clickOffset.left, top: e.pageY - this.clickOffset.top };

			//Call callbacks
			this.propagate("drag", e);
			
			//将helper置于鼠标所在位置处
			this.helper.css({ left: this.position.left+'px', top: this.position.top+'px' }); // Stick the helper to the cursor
			
			return false;
		}
	});
	
})(jQuery);